<?php
namespace app\api\logic;

use app\api\model\User;
use app\common\logic\NoticeLogic;
use app\common\model\AccountLog;
use app\common\model\AfterSale;
use app\common\model\Client_;
use app\common\model\DistributionOrder;
use app\common\model\DistributionOrderGoods;
use app\common\model\Order;
use app\common\model\TeamFollow;
use app\common\model\UserAuth;
use app\common\server\ConfigServer;
use app\common\server\storage\Driver as StorageDriver;
use app\common\server\UrlServer;
use app\common\server\WeChatServer;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\Db;
use app\common\logic\AccountLogLogic;
use think\facade\Cache;

class UserLogic
{
    public static function center($user_id)
    {
        $user = User::get($user_id);
        //待支付
        $user->wait_pay = Db::name('order')->where(['delete_time' => 0, 'user_id' => $user_id, 'order_status' => Order::STATUS_WAIT_PAY, 'pay_status' => 0])->count();
        //待发货
        $user->wait_delivery = Db::name('order')->where(['delete_time' => 0, 'user_id' => $user_id, 'order_status' => [Order::STATUS_WAIT_DELIVERY], 'pay_status' => 1])->count();
        //待收货
        $user->wait_take = Db::name('order')->where(['delete_time' => 0, 'user_id' => $user_id, 'order_status' => [Order::STATUS_WAIT_RECEIVE], 'pay_status' => 1])->count();
        //待评论
        // $user->wait_comment = Db::name('order o')
        //     ->join('order_goods og', 'o.id = og.order_id')
        //     ->where(['user_id' => $user_id, 'order_status' => Order::STATUS_FINISH, 'is_comment' => 0])
        //     ->count('og.id');
        // 售后中
        $user->after_sale = Db::name('after_sale')
            ->where(['delete_time' => 0, 'user_id' => $user_id])
            ->where('status', '<>', AfterSale::STATUS_SUCCESS_REFUND)
            ->count();
        //已完成
         $user->finish = Db::name('order')->where(['delete_time' => 0, 'user_id' => $user_id, 'order_status' => Order::STATUS_FINISH])->count();
        // $user->tian=0;
        // if($user->vip_time>0){
        //     $time=time();
        //     $tian=floor(($user->vip_time-$time)/86400);
        //     $user->tian=$tian>0?$tian:0;
        //     $user->vip_time=date("Y-m-d H:i:s",$user->vip_time);
        // }
        
        $user->visible(['id', 'nickname', 'sn', 'avatar', 'mobile', 'user_money', 'total_order_amount', 'total_recharge_amount',
            'coupon', 'user_integral', 'wait_pay', 'wait_take', 'wait_delivery', 'finish'
            , 'after_sale', 'notice_num','is_new_user','earnings']);

        return $user;
    }

    public static function accountLog($user_id, $source, $type, $page, $size)
    {
        $source_type = '';
        $where[] = ['user_id', '=', $user_id];
        switch ($source) {
            case 1:
                $source_type = AccountLog::money_change;
                break;
            case 2:
                $source_type = AccountLog::integral_change;
                break;
            case 3:
                $source_type = AccountLog::growth_change;
            case 4:
                $source_type = AccountLog::earnings_change;

        }
        $where[] = ['source_type', 'in', $source_type];
        if ($type) {
            $where[] = ['change_type', '=', $type];
        }
        $accountLog = new AccountLog();
        $count = $accountLog
            ->where($where)
            ->count();
        $list = $accountLog
            ->where($where)
            ->page($page, $size)
            ->order('id desc')
            ->field('id,change_amount,source_type,change_type,create_time,remark')
            ->select();
        $more = is_more($count, $page, $size);  //是否有下一页

        $data = [
            'list' => $list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $count,
            'more' => $more
        ];
        return $data;
    }

    //获取用户信息
    public static function getUserInfo($user_id)
    {
        $info = User::where(['id' => $user_id])
            ->field('id,sn,nickname,avatar,mobile,sex,create_time')
            ->find();

        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        
        $info['oa_auth']    = UserAuth::where('user_id', $user_id)->where(Client_::oa)->value('id') ? 1: 0;
        $info['mnp_auth']   = UserAuth::where('user_id', $user_id)->where(Client_::mnp)->value('id') ? 1: 0;
        
        return $info;
    }

    //设置个人信息
    public static function setUserInfo($user_id, $data)
    {
        $field = $data['field'];
        $value = $data['value'];
        $res = Db::name('user')
            ->where(['id' => $user_id])
            ->update([$field => $value]);
        return $res;
    }




    //我的粉丝列表
    public static function fans($user_id, $get, $page, $size)
    {
        $where = [];
        if (isset($get['keyword']) && $get['keyword'] != '') {
            $where[] = ['nickname|mobile', 'like', '%' . $get['keyword'] . '%'];
        }

        //查询条件
        $type = $get['type'] ?? 'all';
        switch ($type) {
            case 'first':
                $where[] = ['first_leader', '=', $user_id];
                break;
            case 'second':
                $where[] = ['second_leader', '=', $user_id];
                break;
            default:
                $where[] = ['first_leader|second_leader', '=', $user_id];
        }

        $field = 'u.id, avatar, nickname, mobile, u.create_time, order_num as fans_order,
                  order_amount as fans_money, fans as fans_team';

        $count = Db::name('user u')
            ->field($field)
            ->leftJoin('user_distribution d', 'd.user_id = u.id')
            ->where($where)
            ->count();

        $lists = Db::name('user u')
            ->field($field)
            ->leftJoin('user_distribution d', 'd.user_id = u.id')
            ->where($where)
            ->page($page, $size)
            ->order(self::fansListsSort($get))
            ->select();

        foreach ($lists as &$item) {
            $item['avatar'] = UrlServer::getFileUrl($item['avatar']);
            $item['fans_team'] = $item['fans_team'] ?? 0;
            $item['fans_order'] = $item['fans_order'] ?? 0;
            $item['fans_money'] = $item['fans_money'] ?? 0;
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            unset($item['fans'], $item['distribution_order_num'], $item['distribution_money']);
        }

        $data = [
            'list' => $lists,
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'more' => is_more($count, $page, $size)
        ];
        return $data;
    }

    /**
     * Notes: 分佣订单列表
     * @param $user_id
     * @param $type
     * @param $page
     * @param $size
     * @return array
     */
    // public static function distribution_order_lists($user_id,$start_data, $page, $size)
    // {
    //     $order = new DistributionOrderGoods();
    //     $where[] = ['dog.delete_time', '=', 0];
    //     $where[] = ['dog.user_id', '=', $user_id];
    //     $where[] = ['dog.status', 'in','1,2'];
    //     if($start_data){
    //         $start_data=$start_data.'-01';
    //         $end_data=$start_data.'-30';
    //         $where[] = ['dog.create_time', '<=',strtotime($start_data)];
    //         $where[] = ['dog.create_time', '>=',strtotime($end_data)];
    //     }
    //     $count = $order::alias('dog')
    //             ->join('order o','o.id=dog.order_id')
    //             ->join('user u', 'u.id = o.user_id')
    //             ->where($where)->count();
    //     $field = [
    //         'dog.level',
    //         'dog.money',
    //         'dog.status'=>'status_desc',
    //         'dog.create_time',
    //         'u.avatar' => 'distribution_avatar',
    //         'u.sn' => 'distribution_sn',
    //         'u.nickname' => 'distribution_nickname',
    //     ];
    //     $lists = $order::alias('dog')
    //             ->join('order o','o.id=dog.order_id')
    //             ->join('user u', 'u.id = o.user_id')
    //             ->where($where)
    //             ->field($field)
    //             ->page($page, $size)
    //             ->order('dog.id desc')
    //             ->select();
    //     foreach ($lists as $key => $value) {
    //         $lists[$key]['distribution_avatar']=UrlServer::getFileUrl($value['distribution_avatar']);
    //         $lists[$key]['create_time']=date('Y-m-d H:i:s',$value['create_time']);
    //     }
    //     $data = [
    //         'list' => $lists,
    //         'page' => $page,
    //         'size' => $size,
    //         'count' => $count,
    //         'more' => is_more($count, $page, $size)
    //     ];
    //     return $data;
    // }


    /**
     * @notes 佣金数据
     * @return array
     * @author Tab
     */
    // public static function distribution_order_info($user_id)
    // {
    //     // 累计已入账佣金
    //     $totalSuccess = DistributionOrderGoods::where([
    //         'status' => 2,
    //         'user_id'=>$user_id
    //     ])->sum('money');
    //     // 累计待结算佣金
    //     $totalWait = DistributionOrderGoods::where([
    //         'status' => 1,
    //         'user_id'=>$user_id
    //     ])->sum('money');
    //     // 累计佣金
    //     $where[]=array('status','in','1,2');
    //     $totalSUM = DistributionOrderGoods::where([
    //         'user_id'=>$user_id
    //     ])->where($where)->sum('money');
    //     return [
    //         'total_success' => $totalSuccess,
    //         'total_sum' => $totalSUM,
    //         'total_wait' => $totalWait,
    //     ];
    // }

}